import { ApiResponse, Diary, DiaryCreate, DiaryListResponse, ChatMessage, AIInsight, Stats } from '../types';

// API基础配置
const API_BASE_URL = typeof process !== 'undefined' && process.env.NODE_ENV === 'development' 
  ? 'http://localhost:8000/api' 
  : 'https://your-domain.com/api';

// 通用请求函数
async function request<T = any>(
  url: string,
  options: any = {}
): Promise<ApiResponse<T>> {
  try {
    // 动态导入Taro以避免编译时错误
    const Taro = await import('@tarojs/taro');
    
    const response = await Taro.default.request({
      url: `${API_BASE_URL}${url}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        ...options.header,
      },
      ...options,
    });

    if (response.statusCode === 200) {
      return {
        success: true,
        data: response.data,
      };
    } else {
      return {
        success: false,
        error: `HTTP ${response.statusCode}`,
      };
    }
  } catch (error) {
    console.error('API请求失败:', error);
    return {
      success: false,
      error: '网络请求失败',
    };
  }
}

// 日记相关API
export const diaryApi = {
  // 获取日记列表
  async getList(page = 1, size = 20, tags?: string[]): Promise<ApiResponse<DiaryListResponse>> {
    const params: any = { page, size };
    if (tags && tags.length > 0) {
      params.tags = tags.join(',');
    }
    
    const queryString = new URLSearchParams(params).toString();
    return request<DiaryListResponse>(`/diaries?${queryString}`);
  },

  // 获取日记详情
  async getDetail(id: number): Promise<ApiResponse<Diary>> {
    return request<Diary>(`/diaries/${id}`);
  },

  // 创建日记
  async create(diary: DiaryCreate): Promise<ApiResponse<Diary>> {
    return request<Diary>('/diaries', {
      method: 'POST',
      data: diary,
    });
  },

  // 更新日记
  async update(id: number, diary: DiaryCreate): Promise<ApiResponse<Diary>> {
    return request<Diary>(`/diaries/${id}`, {
      method: 'PUT',
      data: diary,
    });
  },

  // 删除日记
  async delete(id: number): Promise<ApiResponse<void>> {
    return request<void>(`/diaries/${id}`, {
      method: 'DELETE',
    });
  },

  // 搜索日记
  async search(keyword: string): Promise<ApiResponse<Diary[]>> {
    return request<Diary[]>(`/diaries/search?q=${encodeURIComponent(keyword)}`);
  },
};

// AI功能相关API
export const aiApi = {
  // AI对话
  async chat(message: string): Promise<ApiResponse<{ answer: string; related_diaries: number[] }>> {
    return request('/ai/chat', {
      method: 'POST',
      data: { message },
    });
  },

  // 获取个人洞察
  async getInsights(): Promise<ApiResponse<AIInsight[]>> {
    return request<AIInsight[]>('/ai/insights');
  },

  // 获取写作灵感
  async getInspiration(): Promise<ApiResponse<{ suggestions: string[] }>> {
    return request('/ai/inspire', {
      method: 'POST',
    });
  },

  // 获取对话历史
  async getConversations(): Promise<ApiResponse<ChatMessage[]>> {
    return request<ChatMessage[]>('/ai/conversations');
  },
};

// 统计数据API
export const statsApi = {
  // 获取总体统计
  async getOverview(): Promise<ApiResponse<Stats>> {
    return request<Stats>('/stats/overview');
  },

  // 获取情感统计
  async getEmotions(): Promise<ApiResponse<{ dates: string[]; scores: number[] }>> {
    return request('/stats/emotions');
  },

  // 获取话题统计
  async getTopics(): Promise<ApiResponse<{ tag: string; count: number }[]>> {
    return request('/stats/topics');
  },
}; 